#include "observer.h"
// 观察者类

Observer::Observer(Subject* subject) : subject_(subject) {}
Observer1::Observer1(Subject* subject) : Observer(subject) {
  subject_->Attach(this);
}
void Observer1::Update() {
  std::cout << "Observer1检测到变化" << std::endl;
  // do something,比如执行回调数组
}
// 对象类
// 基类，通过继承防止代码膨胀问题
void Subject::Attach(Observer* observer) { observers_.push_back(observer); }
void Subject::Detach(Observer* observer) {
  for (auto it = observers_.begin(); it != observers_.end(); ++it) {
    if (*it == observer) {
      observers_.erase(it);
      return;
    }
  }
}
void Subject::Notify() {
  for (auto observer : observers_) {
    observer->Update();
  }
}

// 具体对象类
int ConcreteSubjectInt::GetVal() const { return val_; }
void ConcreteSubjectInt::SetVal(const int val) {
  val_ = val;
  Notify();
}